# @Data  : 2020/08/07
# @Author: james
# @Description: 获取本地化消息的类

import os
import configparser
import logging

from ..assistant import FwVariables
from ..exception.errorcode import ErrorCode

logger = logging.getLogger("message")

# 获取localization目录
localization_path = os.path.dirname(os.path.abspath(__file__))


class Message(object):

    def __init__(self):
        language = FwVariables.get_env_language()
        self.language_file = os.path.join(localization_path, language + '.ini')

        # 如果本地语言文件不存在，则使用默认的中文
        if not os.path.exists(self.language_file):
            logger.warning(
                'localization language file {0} not exist, use the default zh language'.format(self.language_file))
            self.language_file = os.path.join(localization_path, 'zh.ini')

        logger.debug('read localization language file %s' % self.language_file)
        self.config = configparser.ConfigParser()
        self.config.read(self.language_file, encoding='utf-8')

    def _get_value(self, section, name, default='not find message define in language file'):
        try:
            res = self.config.get(section, name)
        except:
            logger.error('{section} {option} not define in language file {file}'.format(section=section,
                                                                                        option=name,
                                                                                        file=self.language_file))
            return default
        else:
            return res

    def get_error_message(self, code: ErrorCode):
        """get the error message from error code
        """
        return self._get_value("ERROR", code.name)

    def get_error_type(self, error_type):
        return self._get_value("GENERAL", error_type)


Msg = Message()

if __name__ == '__main__':
    print(Msg.get_error_message(ErrorCode.COMBOBOX_VALUE_NOT_EXIST))
